class Solution {
  public:

    int n, m;
    vector<vector<bool>> vis;
    int solve(vector<vector<char> >& grid) {
        n = grid.size(), m = grid[0].size();
        vis = vector<vector<bool>>(n, vector<bool>(m, false));
        int ret = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (!vis[i][j] && grid[i][j] == '1') {
                    ret++;
                    dfs(grid, i, j);
                }
            }
        }
        return ret;

    }
    int dx[4] = {1, -1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    void dfs(vector<vector<char> >& grid, int i, int j) {
        vis[i][j] = true;
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < n && y >= 0 && y < m && !vis[x][y] && grid[x][y] == '1') {
                dfs(grid, x, y);
            }

        }

    }
};